#!/usr/bin/env bash
. "$GVM_ROOT/scripts/functions"

[[ $1 != "" ]] ||
	display_fatal "Please specify the name"

target_top=$GVM_ROOT
target_set_name=$1
target_set_name_str=$1
add_gopath="$GVM_ROOT/pkgsets/$gvm_go_name/$1"
add_path="$GVM_ROOT/pkgsets/$gvm_go_name/$1/bin"

if [[ $1 == "--local" ]]; then
	LOCAL_TOP=$(find_local_pkgset)
	if [[ ! -d LOCAL_TOP ]]; then
		LOCAL_TOP=$PWD
	fi
	target_top=$LOCAL_TOP/.gvm_local
	target_set_name="local"
	target_set_name_str="__local__"
	add_gopath="$target_top/pkgsets/$gvm_go_name/$target_set_name"
	add_gopath="$LOCAL_TOP:$add_gopath"
	add_path="$target_top/pkgsets/$gvm_go_name/$target_set_name/bin"
	add_path="$LOCAL_TOP/bin:$add_path"
fi

[[ ! -f "$target_top/environments/$gvm_go_name@$target_set_name" ]] ||
	display_fatal "Packageset already exists!"

mkdir -p "$target_top/environments" ||
	display_fatal "Could not create environments folder"
mkdir -p "$target_top/pkgsets/$gvm_go_name/$target_set_name" ||
	display_fatal "Could not create packageset folder"
cp "$GVM_ROOT/environments/$gvm_go_name" "$target_top/environments/$gvm_go_name@$target_set_name" ||
	display_fatal "Could copy environment"
echo "export gvm_pkgset_name=\"$target_set_name_str\"" >> "$target_top/environments/$gvm_go_name@$target_set_name" ||
	display_fatal "Could not extend environment"
echo "export GOPATH; GOPATH=\"$add_gopath:\$GOPATH\"" >> "$target_top/environments/$gvm_go_name@$target_set_name" ||
	display_fatal "Could not extend environment"
echo "export PATH; PATH=\"$add_path:\$PATH\"" >> "$target_top/environments/$gvm_go_name@$target_set_name" ||
	display_fatal "Could not extend environment"

if [ "${target_set_name}" != "global" ]; then
  echo "# Package Set-Specific Overrides" >> "${GVM_ROOT}/environments/${gvm_go_name}@${target_set_name}"
	echo "export GVM_OVERLAY_PREFIX; GVM_OVERLAY_PREFIX=\"\${GVM_ROOT}/pkgsets/${gvm_go_name}/${target_set_name}/overlay\"" >> "${GVM_ROOT}/environments/${gvm_go_name}@${target_set_name}"
  mkdir -p "${GVM_ROOT}/pkgsets/${gvm_go_name}/${target_set_name}/overlay/"{bin,lib/pkgconfig}
  echo "export PATH; PATH=\"${GVM_ROOT}/pkgsets/${gvm_go_name}/${target_set_name}/bin:\${GVM_OVERLAY_PREFIX}/bin:\${PATH}\"" >> "$GVM_ROOT/environments/${gvm_go_name}@${target_set_name}" ||
	  display_fatal "Could not extend environment"
  echo "export LD_LIBRARY_PATH; LD_LIBRARY_PATH=\"\${GVM_OVERLAY_PREFIX}/lib:\${LD_LIBRARY_PATH}\"" >> "${GVM_ROOT}/environments/${gvm_go_name}@${target_set_name}" ||
	  display_fatal "Could not extend environment"
  echo "export DYLD_LIBRARY_PATH; DYLD_LIBRARY_PATH=\"\${GVM_OVERLAY_PREFIX}/lib:\${DYLD_LIBRARY_PATH}\"" >> "${GVM_ROOT}/environments/${gvm_go_name}@${target_set_name}" ||
	  display_fatal "Could not extend environment"
  echo "export PKG_CONFIG_PATH; PKG_CONFIG_PATH=\"\${GVM_OVERLAY_PREFIX}/lib/pkgconfig:\${PKG_CONFIG_PATH}\"" >> "${GVM_ROOT}/environments/${gvm_go_name}@${target_set_name}" ||
	  display_fatal "Could not extend environment"
fi
